package com.opener.web.auth.interceptor;


import com.opener.web.acl.annotation.Auth;
import com.opener.web.auth.constant.AuthConstants;
import com.opener.web.auth.model.UserAuthToken;
import com.opener.web.auth.service.UserAuthService;
import com.opener.web.spring.exception.AuthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author baboy
 * @date 02/12/2016
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserAuthService userAuthService;
    /**
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod method = null;
        if (handler instanceof HandlerMethod){
            method = (HandlerMethod) handler;
        }
        if (method != null){
            Auth auth = null;
            auth = method.getMethodAnnotation(Auth.class);
            //如果不要求验证
            if (auth != null && auth.login() == false){
                return true;
            }
        }

        try {
            UserAuthToken userAuthToken = null;
            userAuthToken = userAuthService.getCheckedAuthToken(request);
            if(userAuthToken == null){
                throw new AuthException("auth.error",request.getRequestURI());
            }
            //设置全局uid
            request.setAttribute(AuthConstants.SessionKey.AUTH_TOKEN, userAuthToken);
            request.setAttribute(AuthConstants.SessionKey.UID, userAuthToken.getUid());
//            User auth = userService.getUser(userAuthToken.getUid());
//
//            //全局使用
//            request.setAttribute(AuthConstants.SessionKey.USER, auth);
//            request.setAttribute(AuthConstants.SessionKey.AUTH_TOKEN, userAuthToken);
            return super.preHandle(request,response,handler) ;
        }catch (Exception e){
            e.printStackTrace();
            throw new AuthException("auth.error",request.getRequestURI());
        }
    }
}
